package initialize

import (
	"fmt"
	"gin-admin/global"
	"sync"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

var dbOnce sync.Once

func InitializeDB() {
	dbOnce.Do(func() {
		postgresConfig := global.GA_CONFIG.Postgres
		dsn := fmt.Sprintf("host=%s port=%v user=%s password=%s dbname=%s sslmode=%s TimeZone=%s",
			postgresConfig.Host,
			postgresConfig.Port,
			postgresConfig.User,
			postgresConfig.Password,
			postgresConfig.DbName,
			postgresConfig.SslMode,
			postgresConfig.TimeZone,
		)
		db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
			NamingStrategy: schema.NamingStrategy{
				SingularTable: true,
				TablePrefix:   "sys_",
			},
		})
		if err != nil {
			global.GA_LOGGER.Sugar().Fatalf("无法连接到 PostgreSQL: %v", err)
		}
		db = db.Debug()
		global.GA_DB = db
		global.GA_LOGGER.Info("数据库连接成功")
	})
}

func CloseDB() {
	db, err := global.GA_DB.DB()
	if err != nil {
		global.GA_LOGGER.Sugar().Fatalf("无法获取数据库对象: %v", err)
	}
	if err := db.Close(); err != nil {
		global.GA_LOGGER.Sugar().Fatalf("关闭数据库连接失败: %v", err)
	}
	global.GA_LOGGER.Info("关闭数据库连接成功")
}
